<template>
  <div class="table-list">
    <div class="list-header">
      <div class="header-title">
        <h3>数据表</h3>
        <el-badge :value="tables.length" class="table-count" />
      </div>
      <div class="header-actions">
        <el-tooltip content="刷新表列表">
          <el-button
            size="small"
            :icon="Refresh"
            @click="$emit('refresh')"
            :loading="loading"
            circle
          />
        </el-tooltip>
      </div>
    </div>

    <!-- 上下文信息 -->
    <div class="context-info" v-if="currentDataSource || currentDatabase">
      <div class="context-item" v-if="currentDataSource">
        <el-icon class="context-icon"><DataBoard /></el-icon>
        <span class="context-label">数据源:</span>
        <span class="context-value">{{ currentDataSource.name }}</span>
      </div>
      <div class="context-item" v-if="currentDatabase">
        <el-icon class="context-icon"><Coin /></el-icon>
        <span class="context-label">数据库:</span>
        <span class="context-value">{{ currentDatabase.name }}</span>
      </div>
    </div>

    <div class="search-box">
      <el-input
        v-model="searchKeyword"
        placeholder="搜索表名..."
        :prefix-icon="Search"
        clearable
        size="small"
      />
    </div>

    <div class="table-items" v-loading="loading">
      <div
        v-for="table in filteredTables"
        :key="table.name"
        class="table-item"
        :class="{ active: selectedTableName === table.name }"
        @click="selectTable(table)"
      >
        <div class="table-info">
          <div class="table-name">
            <el-icon class="table-icon"><Grid /></el-icon>
            {{ table.name }}
          </div>
          <div class="table-meta">
            <span class="table-comment" v-if="table.comment">
              {{ table.comment }}
            </span>
            <span class="table-rows">
              {{ formatNumber(table.rows) }} 行
            </span>
          </div>
        </div>
        
        <div class="table-actions">
          <el-dropdown
            trigger="click"
            @command="handleCommand"
            placement="bottom-end"
          >
            <el-button
              size="small"
              :icon="MoreFilled"
              circle
              @click.stop
            />
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item
                  :command="{ action: 'edit', table: table.name }"
                  :icon="Edit"
                >
                  编辑结构
                </el-dropdown-item>
                <el-dropdown-item
                  :command="{ action: 'copy', table: table.name }"
                  :icon="CopyDocument"
                >
                  复制表
                </el-dropdown-item>
                <el-dropdown-item
                  :command="{ action: 'export', table: table.name }"
                  :icon="Download"
                >
                  导出数据
                </el-dropdown-item>
                <el-dropdown-item
                  :command="{ action: 'truncate', table: table.name }"
                  :icon="Delete"
                  divided
                >
                  清空数据
                </el-dropdown-item>
                <el-dropdown-item
                  :command="{ action: 'delete', table: table.name }"
                  :icon="Delete"
                  class="danger-item"
                >
                  删除表
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </div>

      <!-- 空状态 -->
      <div v-if="!loading && filteredTables.length === 0" class="empty-state">
        <el-empty
          :description="searchKeyword ? '未找到匹配的表' : '暂无数据表'"
          :image-size="80"
        />
      </div>
    </div>

    <!-- 表统计信息 -->
    <div class="table-stats" v-if="tables.length > 0">
      <el-divider />
      <div class="stats-content">
        <div class="stat-item">
          <span class="stat-label">总表数:</span>
          <span class="stat-value">{{ tables.length }}</span>
        </div>
        <div class="stat-item">
          <span class="stat-label">总行数:</span>
          <span class="stat-value">{{ formatNumber(totalRows) }}</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Search,
  Refresh,
  Grid,
  MoreFilled,
  Edit,
  CopyDocument,
  Download,
  Delete,
  DataBoard,
  Coin
} from '@element-plus/icons-vue'

export default {
  name: 'TableList',
  components: {
    Search,
    Refresh,
    Grid,
    MoreFilled,
    Edit,
    CopyDocument,
    Download,
    Delete,
    DataBoard,
    Coin
  },
  props: {
    tables: {
      type: Array,
      default: () => []
    },
    loading: {
      type: Boolean,
      default: false
    },
    currentDataSource: {
      type: Object,
      default: null
    },
    currentDatabase: {
      type: Object,
      default: null
    }
  },
  emits: ['select-table', 'delete-table', 'refresh'],
  setup(props, { emit }) {
    const searchKeyword = ref('')
    const selectedTableName = ref('')

    // 过滤后的表列表
    const filteredTables = computed(() => {
      if (!searchKeyword.value) {
        return props.tables
      }
      
      const keyword = searchKeyword.value.toLowerCase()
      return props.tables.filter(table => 
        table.name.toLowerCase().includes(keyword) ||
        (table.comment && table.comment.toLowerCase().includes(keyword))
      )
    })

    // 总行数
    const totalRows = computed(() => {
      return props.tables.reduce((total, table) => total + (table.rows || 0), 0)
    })

    // 格式化数字
    const formatNumber = (num) => {
      if (num >= 1000000) {
        return (num / 1000000).toFixed(1) + 'M'
      } else if (num >= 1000) {
        return (num / 1000).toFixed(1) + 'K'
      }
      return num.toString()
    }

    // 选择表
    const selectTable = (table) => {
      selectedTableName.value = table.name
      emit('select-table', table.name)
    }

    // 处理下拉菜单命令
    const handleCommand = async (command) => {
      const { action, table } = command
      
      switch (action) {
        case 'edit':
          selectedTableName.value = table
          emit('select-table', table)
          break
          
        case 'copy':
          await handleCopyTable(table)
          break
          
        case 'export':
          await handleExportTable(table)
          break
          
        case 'truncate':
          await handleTruncateTable(table)
          break
          
        case 'delete':
          await handleDeleteTable(table)
          break
      }
    }

    // 复制表
    const handleCopyTable = async (tableName) => {
      try {
        const { value: newTableName } = await ElMessageBox.prompt(
          `请输入新表名（复制自 ${tableName}）:`,
          '复制表',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            inputPattern: /^[a-zA-Z_][a-zA-Z0-9_]*$/,
            inputErrorMessage: '表名只能包含字母、数字和下划线，且不能以数字开头'
          }
        )
        
        // 模拟复制操作
        await new Promise(resolve => setTimeout(resolve, 1000))
        
        ElMessage.success(`表 "${tableName}" 已复制为 "${newTableName}"`)
        emit('refresh')
      } catch (error) {
        // 用户取消操作
      }
    }

    // 导出表数据
    const handleExportTable = async (tableName) => {
      try {
        await ElMessageBox.confirm(
          `确定要导出表 "${tableName}" 的数据吗？`,
          '导出确认',
          {
            confirmButtonText: '导出',
            cancelButtonText: '取消',
            type: 'info'
          }
        )
        
        // 模拟导出操作
        await new Promise(resolve => setTimeout(resolve, 2000))
        
        ElMessage.success(`表 "${tableName}" 数据导出成功`)
      } catch (error) {
        // 用户取消操作
      }
    }

    // 清空表数据
    const handleTruncateTable = async (tableName) => {
      try {
        await ElMessageBox.confirm(
          `确定要清空表 "${tableName}" 的所有数据吗？此操作不可恢复。`,
          '清空确认',
          {
            confirmButtonText: '清空',
            cancelButtonText: '取消',
            type: 'warning',
            confirmButtonClass: 'el-button--warning'
          }
        )
        
        // 模拟清空操作
        await new Promise(resolve => setTimeout(resolve, 1000))
        
        ElMessage.success(`表 "${tableName}" 数据已清空`)
        emit('refresh')
      } catch (error) {
        // 用户取消操作
      }
    }

    // 删除表
    const handleDeleteTable = async (tableName) => {
      emit('delete-table', tableName)
    }

    return {
      searchKeyword,
      selectedTableName,
      filteredTables,
      totalRows,
      formatNumber,
      selectTable,
      handleCommand
    }
  }
}
</script>

<style scoped>
.table-list {
  height: 100%;
  display: flex;
  flex-direction: column;
  background: white;
}

.list-header {
  padding: 16px;
  border-bottom: 1px solid #f0f0f0;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-title {
  display: flex;
  align-items: center;
  gap: 8px;
}

.header-title h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.table-count {
  :deep(.el-badge__content) {
    background-color: #409eff;
  }
}

.context-info {
  padding: 8px 16px;
  background-color: #f8f9fa;
  border-bottom: 1px solid #e9ecef;
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.context-item {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 12px;
}

.context-icon {
  color: #409eff;
  font-size: 14px;
}

.context-label {
  color: #606266;
  font-weight: 500;
}

.context-value {
  color: #303133;
  font-weight: 600;
}

.search-box {
  padding: 0 16px 16px;
}

.table-items {
  flex: 1;
  overflow-y: auto;
  padding: 0 8px;
}

.table-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px 8px;
  margin-bottom: 4px;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.2s;
  border: 1px solid transparent;
}

.table-item:hover {
  background-color: #f5f7fa;
  border-color: #e4e7ed;
}

.table-item.active {
  background-color: #ecf5ff;
  border-color: #409eff;
}

.table-info {
  flex: 1;
  min-width: 0;
}

.table-name {
  display: flex;
  align-items: center;
  gap: 6px;
  font-weight: 500;
  color: #303133;
  margin-bottom: 4px;
}

.table-icon {
  color: #909399;
  font-size: 14px;
}

.table-meta {
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.table-comment {
  font-size: 12px;
  color: #606266;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.table-rows {
  font-size: 11px;
  color: #909399;
}

.table-actions {
  opacity: 0;
  transition: opacity 0.2s;
}

.table-item:hover .table-actions {
  opacity: 1;
}

.empty-state {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 200px;
}

.table-stats {
  padding: 16px;
}

.stats-content {
  display: flex;
  justify-content: space-around;
}

.stat-item {
  text-align: center;
}

.stat-label {
  font-size: 12px;
  color: #909399;
  display: block;
  margin-bottom: 4px;
}

.stat-value {
  font-size: 14px;
  font-weight: 600;
  color: #303133;
}

:deep(.danger-item) {
  color: #f56c6c;
}

:deep(.danger-item:hover) {
  background-color: #fef0f0;
}
</style>